package com.ftg.learn.psi.service.impl;

import com.ftg.learn.psi.Dto.PurchaseParam;
import com.ftg.learn.psi.entity.PurchaseDetail;
import com.ftg.learn.psi.entity.PurchaseOrder;
import com.ftg.learn.psi.mapper.ItemMapper;
import com.ftg.learn.psi.mapper.PurchaseOrderMapper;
import com.ftg.learn.psi.service.IPurchaseDetailService;
import com.ftg.learn.psi.service.IPurchaseOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ftg.learn.psi.utils.SnowFlake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 进货订单表 服务实现类
 * </p>
 *
 * @author guoBingTong
 * @since 2022-05-18
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {

    @Autowired
    IPurchaseDetailService iPurchaseDetailService;

    @Autowired
    ItemMapper itemMapper;

    /**
     * 进货模块
     * 添加进货订单表,同时添加进货订单明细表,并添加商品的库存。
     * @param purchaseParam
     * @return
     */
    @Override
    @Transactional(rollbackFor = SQLException.class)
    public boolean insertPurchaseOrder(PurchaseParam purchaseParam){
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        BeanUtils.copyProperties(purchaseParam,purchaseOrder);
        SnowFlake idWorker = new SnowFlake(0, 0);
        long order = idWorker.nextId();
        String orderNo = String.valueOf(order);
        purchaseOrder.setOrderNo(orderNo);
        purchaseOrder.setCreateTime(LocalDateTime.now());
        this.save(purchaseOrder);

        for (PurchaseDetail purchaseDetail : purchaseParam.getPurchaseDetailList()) {
            purchaseDetail.setPurchaseOrderId(purchaseOrder.getId());
            iPurchaseDetailService.save(purchaseDetail);
            itemMapper.addCount(purchaseDetail.getCount(),purchaseDetail.getItemId());
        }
        return true;
    }
}
